// pages/publishDetail/index.ts

import { selectRecord } from "../../service/api/api-publicity-record";
import { fontSizeCalc } from "../../utils/util";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    recordId: 0,// 纪录id
    record: {
      isEmploy: 1
    },// 纪录详情
    access: {} as any,// 当前用户权限
    currentUser: {},// 当前用户信息
    options: '',
    isAdmin: false,// 是否是管理员查看详情
    iconSize: fontSizeCalc(40),
    tabFontSize: fontSizeCalc(28),
    labelSize: fontSizeCalc(28),
    inputSize: fontSizeCalc(32),
    btnHeight: fontSizeCalc(60) + 'rpx',
    btnLineHeight: fontSizeCalc(36) + 'rpx',
    btnWidth: fontSizeCalc(320) + 'rpx',
    currentSource: 0,// 来源收缩显示
    currentName: 0,// 单位收缩显示
    sourceTagColor: '',
    annexList: [],
    fileUrlArr: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const recordId = options.id || 0;
    const { globalData: { access, currentUser } } = getApp();
    this.setData({
      access,
      recordId: recordId,
      isAdmin: access.宣传刊播x配置x管理员,
      currentUser,
      options: JSON.stringify(options)
    })
    this.getRecordDetail(recordId);


  },

  /**
   * 处理一下纪录状态
   * @param data
   */
  handleRecordType({ state }) {
    return {
      typeName: state === 1 ? '开启' : '关闭',
      bgColor: state === 1 ? '#389E0D' : '#F5A34D',
    }
  },

  /**
   * 通过id获取纪录详情
   * @param id
   */
  async getRecordDetail(id) {
    let _that = this;
    wx.showLoading({
      title: '查询中...'
    })
    // 执行搜索函数
    await selectRecord({ id }).then(async (response) => {
      wx.hideLoading();
      const newRecord = response.data || {};
      const {
        typeName,
        bgColor
      } = this.handleRecordType(newRecord);
      newRecord.bgColor = bgColor;
      newRecord.typeName = typeName;
      newRecord.publishTime = newRecord.publishTime?.split(' ')[0]
      newRecord.createdTime = newRecord.createdTime?.split(' ')[0]
      _that.setData({
        record: response.data || {}
      })
      const topName = this.data.record.sourceTopName;
      this.setData({
        sourceTagColor: topName == "中央媒体" ? "#F54341" : topName == "市/区县级媒体" ? "#FFA39E" : "#91D5FF",
        annexList: this.data.record.attachments
      })
      console.log(this.data.record);
    }).catch(error => {
      console.warn(error)
      wx.showToast({
        title: error || '查询失败',
        icon: 'error',
        duration: 1500
      })
      wx.hideLoading();
    }).finally(() => {
      wx.hideLoading();
    })
  },
  changeCollapse(e: any) {
    const curTag = e.currentTarget.dataset.item || '';
    this.setData({
      [curTag]: this.data[curTag] === 0 ? 1 : 0
    })
  },
  /**
     * 附件预览
     * 
  */
  previewFile(e: any) {
    let filePath = e.currentTarget.dataset.path;
    if (!filePath) {
      return;
    };
    wx.downloadFile({
      url: filePath,
      success(res) {
        if (res.statusCode === 200) {
          var Path = res.tempFilePath //返回的文件临时地址，用于后面打开本地预览所用
          var fileName = e.currentTarget.dataset.name
          var type = fileName.split('.').pop()
          wx.openDocument({
            filePath: Path,
            showMenu: true,
            fileType: type,
            success: function (res) {
              console.log('打开成功');
            }
          })
        }
      }
    })
  },
  /**
     * 附件删除
     * 
  */
  deleteFile(e: any) {
    let path = e.currentTarget.dataset.path;
    let value = this.data.fileUrlArr;
    let filterValue = value.filter(function (element, index, self) {
      return element.path != path;
    });
    this.setData({
      'fileUrlArr': filterValue
    });
  },
  /**
    * 点击复制
    * 
 */
  clipboard: function (e) {
    let name = e.currentTarget.dataset.name;
    wx.setClipboardData({
      data: name, //复制的数据
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            console.log(res.data) //打印赋值的数据
            wx.showToast({
              title: '复制成功',
            })
          }
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    wx.hideShareMenu({
      menus: ['shareAppMessage', 'shareTimeline'],// 隐藏分享到朋友和分享到朋友圈
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  taskExecuteShareFun() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
  }
})